<template>
  <div class="user-profile">
    <van-nav-bar
      class="page-nav-bar"
      title="个人信息"
      left-arrow @click-left="$router.back()"
    />

    <input type="file" ref="inputFile" hidden @change="inputChange">
    <van-cell title="头像" is-link @click="$refs.inputFile.click()">
      <van-image
        class="avatar"
        fit="cover"
        round
        :src="user.photo"
      />
    </van-cell>

    <van-cell title="昵称" :value="user.name" is-link @click="isShowUpdateName = true"/>
    <van-cell title="性别" :value="user.gender === 0 ? '男' : '女'" is-link @click="isShowUpdateGender = true"/>
    <van-cell title="生日" :value="user.birthday" is-link  @click="isShowUpdateBirThday = true"/>

    <van-popup
      v-model="isShowUpdateName"
      style="height: 100%"
      position="bottom">
      <update-name
        v-if="isShowUpdateName"
        v-model="user.name"
        @close="isShowUpdateName = false"
      />
    </van-popup>

    <van-popup
      v-model="isShowUpdateBirThday"
      position="bottom">
      <update-birthday
        v-if="isShowUpdateBirThday"
        v-model="user.birthday"
        @close="isShowUpdateBirThday = false"
      />
    </van-popup>

    <van-popup
      v-model="isShowUpdateGender"
      position="bottom">
      <update-gender
        v-if="isShowUpdateGender"
        v-model="user.gender"
        @close="isShowUpdateGender = false"
      />
    </van-popup>

    <van-popup
      v-model="isShowUpdateImg"
      style="height: 100%"
      position="bottom">
      <update-img
        v-if="isShowUpdateImg"
        :img="imgUrl"
        @close="isShowUpdateImg = false"
        @update-avatar="user.photo = $event"
      />
    </van-popup>
  </div>
</template>

<script>
import {getUserProfile} from '@/api/user'
import UpdateName from './components/update-name'
import UpdateGender from './components/update-gender'
import UpdateBirthday from './components/update-birthday'
import UpdateImg from './components/update-img'

export default {
  name: 'user-profile',
  components: {
    UpdateName,
    UpdateGender,
    UpdateBirthday,
    UpdateImg
  },
  created() {
    this.getUser()
  },
  data () {
    return {
      user: {},
      imgUrl: '',
      isShowUpdateName: false,
      isShowUpdateGender: false,
      isShowUpdateBirThday: false,
      isShowUpdateImg: false
    }
  },
  methods: {
    async getUser() {
      try {
        const { data: {data} } = await getUserProfile()

        this.user = data
      }catch(err) {
        console.log(err)
      }
    },
    inputChange () {
      const file = this.$refs.inputFile.files[0]

      this.imgUrl = window.URL.createObjectURL(file)

      this.isShowUpdateImg = true

      this.$refs.inputFile.value = ''
    }
  }
}
</script>

<style scoped lang='less'>
.user-profile {
  .avatar {
    width: 60px;
    height: 60px;
  }
}
</style>
